package cn.com.yang.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.collections.map.HashedMap;

/**
 * 自定义HTTP服务器 TODO
 * 
 * @author yangyijin
 * @since 2023年5月13日-下午8:22:27
 */
public class ServerSocket8080 {
	public static void main(String[] args) throws IOException {
		// ServerSocketChannel; AIO
		ServerSocket serverSocket = new ServerSocket(8080);//
		ExecutorService pool = Executors.newCachedThreadPool();
		while (true) {
			Socket client = serverSocket.accept();// 阻塞获取客户端
			pool.execute(() -> {
				try (InputStream inputStream = client.getInputStream(); OutputStream out = client.getOutputStream();) {
//					byte[] buf = new byte[1024];
//					int hasRead = 0;
//					while ((hasRead = inputStream.read(buf)) != -1) {
//						System.out.println("字节输入信息：");
//						System.out.print(new String(buf, 0, hasRead));
//					}
					byte[] bytes = new byte[inputStream.available()];
                    int result = inputStream.read(bytes);//
                    if (result != -1) {
                        System.out.println("字节输入流信息 ： 👇  👇  👇");
                        System.out.println(new String(bytes));
                    }
                    Map map = new HashedMap();
                    map.put("name", "yidashi");
					String response = HTTPResponse.getResponseLine() + HTTPResponse.getResponseHeader() + "\n" + HTTPResponse.getResponseBody(map);
					out.write(response.getBytes());
					out.flush();
					client.shutdownInput();
					client.shutdownOutput();
					client.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			});
		}
	}

	
}
